package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.aliyun.oss.internal.OSSUtils;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Focus;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.XzjVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserInfoService {
    @DubboReference
    private FocusApi focusApi;


    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference

    private RecommendUserApi recommendUserApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    public MessagesService messagesService;

    @Autowired
    private RedisTemplate redisTemplate;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map counts() {
        Long userId = UserHolder.getUserId();
        //统计互相喜欢
        long eachLoveCount = friendApi.count(userId);
        //统计我喜欢和喜欢我的粉丝数
        Map counts = userLikeApi.count(userId);

        counts.put("eachLoveCount",eachLoveCount);

        return counts;
    }


    /**
     * 更新用户头像
     * @param headPhoto 用户头像
     * @param id 用户id
     * @throws IOException
     * 赵旭飞
     */
    public void updateUserHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1如果没有人脸，返回信息："图片非人像，请重新上传!"
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            //根据用户id查一下当前用户的userInfo获取旧图片地址，调用删除方法，删除oss中旧的图片
            userInfoApi.update(userInfo);
        }

    }

    //相互喜欢、喜欢、粉丝、谁看过我

    public PageResult friendsType(Integer page, Integer pagesize, String nickname, Integer type) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //用户集合
        Map<Long, UserInfo> userInfoMap = new HashMap<>();
        //用户id
        Set<Long> userIds = new HashSet<>();
        //所有的用户
        List<Long> focus = new ArrayList<>();

        if (type == 1) {
            //互相关注
            ArrayList<Long> longs = new ArrayList<>();
            //根据用户id在redis中拿到用户id
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(Constants.FOCUS_USER_KEY + userId);
            Set<Object> objects = entries.keySet();
            for (Object object : objects) {
                Long id = Long.valueOf(object.toString());
                longs.add(id);
            }
            //判断是否存在互相关注
            for (Long aLong : longs) {
                Object o = redisTemplate.opsForHash().get(Constants.FOCUS_USER_KEY + aLong, userId.toString());
                if (o != null) {
                    //互相关注
                    focus.add(aLong);
                }
            }
        } else if (type == 2) {
            //我关注
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(Constants.FOCUS_USER_KEY + userId);
            Set<Object> objects = entries.keySet();
            for (Object object : objects) {
                Long id = Long.valueOf(object.toString());
                focus.add(id);
            }

        } else if (type == 3) {
            //粉丝
            //查表
            focus = focusApi.getByUserId(userId);
        } else if (type == 4) {
            //谁看过我
            //拿到访客的用户id
            List<Visitors> visitorsList = visitorsApi.getVisitorsByUserId(userId);
            focus = CollUtil.getFieldValues(visitorsList, "visitorUserId", Long.class);
        }

        //构造返回的对象
        PageResult result = new PageResult();
        //总条数
        int size = focus.size();
        if (focus == null || size == 0) {
            result.setItems(new ArrayList<>());
            return result;
        }

        //拿到互相关注的用户的id
        userInfoMap = userInfoApi.getByIds(page, pagesize, nickname, focus);
        userIds = userInfoMap.keySet();
        //是否喜欢Ta
        Map<Long, Boolean> alreadyLoveMap = userLikeApi.alreadyLove(userId, userIds);
        //匹配度
        Map<Long, Integer> matchRateMap = recommendUserApi.matchRate(userId, userIds);

        List<XzjVo> xzjVoList = new ArrayList<>();
        //赋值
        Collection<UserInfo> values = userInfoMap.values();
        for (UserInfo userInfo : values) {
            XzjVo xzjVo = new XzjVo();
            //用户详细信息
            BeanUtils.copyProperties(userInfo, xzjVo);

            //匹配度
            Integer matchRate = matchRateMap.get(userInfo.getId());
            if (matchRate == null) {
                Random random = new Random();
                matchRate = random.nextInt(9) + 90;
            }
            xzjVo.setMatchRate(matchRate);

            //是否喜欢Ta
            Boolean aBoolean = alreadyLoveMap.get(userInfo.getId());
            if (aBoolean == null) {
                aBoolean = false;
            }
            xzjVo.setAlreadyLove(aBoolean);
            //添加进集合
            xzjVoList.add(xzjVo);
        }
        result.setCounts(Long.valueOf(size));
        result.setItems(xzjVoList);
        result.setPage(page);
        result.setPagesize(pagesize);
        result.setPage((int) Math.ceil(result.getCounts() * 1.0 / pagesize));
        return result;
    }

    public void fansLike(Long uid) {
        //拿到用户id
        Long userId = UserHolder.getUserId();
        //构造保存的对象
        Focus focus = new Focus();
        focus.setCreateDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        focus.setUserId(uid);
        focus.setToUserId(userId);
        //保存
        focusApi.save(focus);
        //保存到redis中
        redisTemplate.opsForHash().put(Constants.FOCUS_USER_KEY + uid, userId.toString(), "1");
    }

    public void removeLike(Long uid) {
        //拿到用户id
        Long userId = UserHolder.getUserId();
        //删除
        focusApi.delete(uid, userId);
        //从redis中删除
        redisTemplate.opsForHash().get(Constants.FOCUS_USER_KEY + uid, userId.toString());
    }
}


